#!/usr/bin/env python
import os, sys
import xml.dom.minidom
import account

class cfg:
   notifications = {
      'sounds': [True,{
         'buddy-online': 'sounds/online.wav',
         'buddy-offline': 'sounds/offline.wav',
         'buddy-message': 'sounds/message.wav',
         'buddy-invite': 'sounds/invite.wav',
         'client-online': 'sounds/me_online.wav',
         'client-offline': 'sounds/me_offline.wav',
         'buddy-received-file': 'sounds/file.wav',
      }],
      'text': True
   };
   
   host = 'stream.mxit.co.za';
   port = 9119;
   hideOfflineContacts = False;
   #language = 'en_GB';
   timeformat = '%H:%M:%S';
   debug = False;
   autoAway = (True,10);
   log = False;
   offlineMessage = (False,"");
   msgColour = (False,"#000000");


class config:

   def __init__(self):
      self.parser = xml.dom.minidom.parse(open('settings.xml'));

   def save(self,conf,updatedAccount):
      # Create account stuff
      accounts = self.parser.getElementsByTagName("accounts")[0];
      # delete the old <account>
      acc = accounts.getElementsByTagName("account");
      if len(acc) > 0:
         accounts.removeChild(acc[0]);
      account = self.parser.createElement("account");
      
      alias = self.parser.createElement("alias");
      alias.appendChild(self.parser.createTextNode(updatedAccount.alias));
      account.appendChild(alias);

      username = self.parser.createElement("username");
      username.appendChild(self.parser.createTextNode(updatedAccount.username));
      account.appendChild(username);

      password = self.parser.createElement("password");
      if updatedAccount.rememberPassword == True:
         password.appendChild(self.parser.createTextNode(updatedAccount.password));
      else:
         password.appendChild(self.parser.createTextNode(""));
      account.appendChild(password);

      auth = self.parser.createElement("auth");
      auth.appendChild(self.parser.createTextNode(updatedAccount.auth));
      account.appendChild(auth);

      lang = self.parser.createElement("lang");
      lang.appendChild(self.parser.createTextNode(updatedAccount.lang));
      account.appendChild(lang);
      
      account.setAttribute('autologin',str(updatedAccount.autologin));
     
      accounts.appendChild(account);

      # Create notifications stuff
      notifications = self.parser.getElementsByTagName("notifications");
      
      snds = notifications[0].getElementsByTagName('sounds');
      sounds = snds[0].setAttribute('enabled',str(conf.notifications['sounds'][0]));
      lemts = snds[0].getElementsByTagName('sound');
      for i in range(0,len(lemts)):
         id = str(lemts[i].getAttribute('id'));
         try:
            d = conf.notifications['sounds'][1][id];
            lemts[i].setAttribute('file',d);
         except:
            pass;

      txt = notifications[0].getElementsByTagName('text')[0];
      txt.setAttribute('enabled',str(conf.notifications['text']));


      # Create server stuff
      server = self.parser.getElementsByTagName("server");
      address = server[0].getElementsByTagName('address')[0];
      if address.hasChildNodes():
         address.removeChild(address.childNodes[0]);
      address.appendChild(self.parser.createTextNode(conf.host));

      port = server[0].getElementsByTagName('port')[0];
      if port.hasChildNodes():
         port.removeChild(port.childNodes[0]);
      port.appendChild(self.parser.createTextNode(str(conf.port)));
      
      # Create preferences stuff
      prefs = self.parser.getElementsByTagName('preferences');
      
      # log to local
      lTL = prefs[0].getElementsByTagName("logToLocal");
      if conf.log == True:
         if len(lTL) == 0:
            log = self.parser.createElement("logToLocal");
            prefs[0].appendChild(log);
      else:
         if len(lTL) > 0:
            prefs[0].removeChild(lTL[0]);

      # date format
      dF = prefs[0].getElementsByTagName("dateFormat");
      if len(dF) == 0:
         dF = self.parser.createElement("dateFormat");
         prefs[0].appendChild(dF);
      dF = prefs[0].getElementsByTagName("dateFormat")[0];
      if dF.hasChildNodes():
         dF.removeChild(dF.childNodes[0]);
      dF.appendChild(self.parser.createTextNode(conf.timeformat));
      
      
      # hide offline
      hO = prefs[0].getElementsByTagName("hideOffline");
      if conf.hideOfflineContacts == True:
         if len(hO) == 0:
            log = self.parser.createElement("hideOffline");
            prefs[0].appendChild(log);
      else:
         if len(hO) > 0:
            prefs[0].removeChild(hO[0]);
            
      # offline messages
      mC = prefs[0].getElementsByTagName("msgColour");
      if conf.msgColour[0] == True:
         if len(mC) == 0:
            mC = self.parser.createElement("msgColour");
            prefs[0].appendChild(mC);
            
         mC = prefs[0].getElementsByTagName("msgColour")[0];
         if mC.hasChildNodes():
            mC.removeChild(mC.childNodes[0]);
         mC.appendChild(self.parser.createTextNode(conf.msgColour[1]));
      else:
         if len(mC) > 0:
            prefs[0].removeChild(mC[0]);

      # auto away
      aA = prefs[0].getElementsByTagName("autoAway");
      if conf.autoAway[0] == True:
         if len(aA) == 0:
            aA = self.parser.createElement("autoAway");
            prefs[0].appendChild(aA);
            
         aA = prefs[0].getElementsByTagName("autoAway")[0];
         aA.setAttribute('period',str(conf.autoAway[1]));
      else:
         if len(aA) > 0:
            prefs[0].removeChild(aA[0]);

      # offline messages
      oM = prefs[0].getElementsByTagName("offlineMessage");
      if conf.offlineMessage[0] == True:
         if len(oM) == 0:
            oM = self.parser.createElement("offlineMessage");
            prefs[0].appendChild(oM);
            
         oM = prefs[0].getElementsByTagName("offlineMessage")[0];
         if oM.hasChildNodes():
            oM.removeChild(oM.childNodes[0]);
         oM.appendChild(self.parser.createTextNode(conf.offlineMessage[1]));
      else:
         if len(oM) > 0:
            prefs[0].removeChild(oM[0]);

      # debug
      dbg = prefs[0].getElementsByTagName("debug");
      if conf.debug == True:
         if len(dbg) == 0:
            dbg = self.parser.createElement("debug");
            prefs[0].appendChild(dbg);
      else:
         if len(dbg) > 0:
            prefs[0].removeChild(dbg[0]);

      data = self.parser.toxml();
      f = open('settings.xml','w');
      f.write(data);
      f.close();

   # Get account details
   def getAccount(self):
    
      acc = self.parser.getElementsByTagName("account")[0];

      if acc.getAttribute("autologin").upper() == 'TRUE':
         auto = True;
      else:
         auto = False;

      alias = str(acc.getElementsByTagName("alias")[0].childNodes[0].data);
      id = str(acc.getElementsByTagName("username")[0].childNodes[0].data);
      try:
         pin = str(acc.getElementsByTagName("password")[0].childNodes[0].data);
      except:
         pin = "";

      auth = str(acc.getElementsByTagName("auth")[0].childNodes[0].data);
      lang = str(acc.getElementsByTagName("lang")[0].childNodes[0].data);
      acnt = account.Account(alias,id,pin,auth,auto,lang);

      return acnt;

      
   def getConfig(self):
      conf = cfg();

      # Notifications settings
      notifications = self.parser.getElementsByTagName("notifications");
      if len(notifications) > 0:
      
         snds = notifications[0].getElementsByTagName("sounds");
         # SOUNDS
         if len(snds) > 0:
            if snds[0].getAttribute("enabled").upper() == 'TRUE':
               conf.notifications['sounds'][0] = True;
            else:
               conf.notifications['sounds'][0] = False;            
            s = snds[0].getElementsByTagName("sound");
            for i in range(0,len(s)):
               name = str(s[i].getAttribute("id"));
               conf.notifications['sounds'][1][name] = str(s[i].getAttribute("file"));

         # TEXT         
         text = notifications[0].getElementsByTagName("text");
         if len(text) > 0:
            if text[0].getAttribute("enabled").upper() == 'TRUE':
               conf.notifications['text'] = True;
            else:
               conf.notifications['text'] = False;            

            
      # Server settings
      server = self.parser.getElementsByTagName("server");
      if len(server) > 0:
         address = server[0].getElementsByTagName("address");
         if len(address) > 0:
            conf.host = str(address[0].childNodes[0].data);
         
         port = server[0].getElementsByTagName("port");
         if len(port) > 0:
            conf.port = int(port[0].childNodes[0].data);

      # Preferences settings
      prefs = self.parser.getElementsByTagName("preferences");
      if len(prefs) > 0:
         logToLocal = prefs[0].getElementsByTagName("logToLocal");
         if len(logToLocal) > 0:
            conf.log = True;

         dateFormat = prefs[0].getElementsByTagName("dateFormat");
         if len(dateFormat) > 0:
            conf.timeformat = str(dateFormat[0].childNodes[0].data);
            
         # Hide offline contacts?
         oC = prefs[0].getElementsByTagName("hideOffline");
         if len(oC) > 0:
            conf.hideOfflineContacts = True;
         
         # Auto Away
         aA = prefs[0].getElementsByTagName("autoAway");
         if len(aA) > 0:
            period = int(aA[0].getAttribute("period"));
            conf.autoAway = (True,period);
         else:
            conf.autoAway = (False,10);
            
         # Message Colour
         mC = prefs[0].getElementsByTagName("msgColour");
         if len(mC) > 0:
            colour = str(mC[0].childNodes[0].data);
            conf.msgColour = (True,colour.upper());
         else:
            conf.msgColour = (False,'#000000');

         # Debug mode
         debug = prefs[0].getElementsByTagName("debug");
         if len(debug) > 0:
            conf.debug = True;
         
         # Offline message
         oM = prefs[0].getElementsByTagName("offlineMessage");
         if len(oM) > 0:
            msg = str(oM[0].childNodes[0].data);
            conf.offlineMessage = (True,msg);       
      

      return conf;
   
   def getFirstTime(self):
      # Look to see if account information
      # is there. If not, then it is the first time
      # so return True.
      if len(self.parser.getElementsByTagName("account")) == 0:
         return True;
      else:
         return False;